// var Utils = require('./utils.js');
var QQMapWX = require('./libs/qqmap-wx-jssdk.js');
var config = require('../../../config/index')

var qqmapsdk = new QQMapWX({
  key: 'LMWBZ-YKB3L-L53PL-EQCI3-RCZAV-RKBMX' //在这里输入你在腾讯位置服务平台申请的KEY
});
var timer;
const formatTime = function () {
  const date = new Date();
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekDay = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return {
    date: [year, month, day].map(formatNumber).join('-'),
    time: [hour, minute, second].map(formatNumber).join(':'),
    week: '星期' + weekDay
  }
}

const formatNumber = function (n) {
  const s = n.toString()
  return s[1] ? s : '0' + s
}
Page({
  data: {
    device: 'back',
    flash: '',
    date: "",
    time: "",
    week: "",
    address: "",
    addressName: "",
    cameraWidth: 0,
    cameraHeight: 0,
    canvasWidth: 0,
    canvasHeight: 0,
    remarks:""
  },
  getAuth: function () {
    wx.getSetting({
      success: res => {
        console.log(res.authSetting)
        this.setData({
          camera: res.authSetting['scope.camera'],
          writePhotosAlbum: res.authSetting['scope.writePhotosAlbum'],
          userLocation: res.authSetting['scope.userLocation']
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const systemInfo = wx.getSystemInfoSync();
    const screenWidth = systemInfo.screenWidth;
    const screenHeight = systemInfo.screenHeight;
    const statusBarHeight = systemInfo.statusBarHeight;
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    const cameraWidth = screenWidth;
    const cameraHeight = screenHeight - statusBarHeight - menuButtonInfo.height - (menuButtonInfo.top -
      systemInfo.statusBarHeight) * 2 - 90;

    console.log(systemInfo)
    this.setData({
      cameraWidth: cameraWidth,
      cameraHeight: cameraHeight
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getTime()
    this.getLocation()
    this.getAuth()
  },

  /**
   * 获取当前时间
   */
  getTime: function () {
    timer = setInterval(() => {
      let timeData = formatTime()
      this.setData({
        date: timeData.date,
        time: timeData.time,
        week: timeData.week
      })
    }, 1000)
  },
  remark(e){
    var that = this
    wx.showModal({
      editable:true,
      placeholderText:'请输入备注',
      title: '备注',
      content:that.data.remarks,
      complete: (res) => {
        if (res.cancel) {
          
        }
        if (res.confirm) {
          that.setData({
            remarks:res.content
          })
        }
      }
    })
    console.log(e)
  },
  /**
   * 获取地址信息
   */
  getLocation: function () {
    wx.getLocation({
      success: res => {
        console.log(res)
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: res => {
            console.log(res)
            let address = res.result.address;
            this.setData({
              address
            })
          },
          fail(error) {
            console.log(error)
          }
        })
      }
    })
  },

  /**
   * 图片安全检测
   */
  checkImage: function (imageUrl) {
    //自己去接入一下
    return new Promise((resolve, reject) => {
      wx.request({
        url: checkApi,
        method: "POST",
        data: {
          image: imageUrl
        },
        success: res => {
          wx.hideLoading()
          resolve(res.data.errcode)
          if (res.data.errcode == 0) {} else if (res.data.errcode == 87014) {
            wx.showModal({
              title: '温馨提示',
              content: '您的照片存在违规内容，请规范本小程序使用。',
              showCancel: false,
              complete: (res) => {
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              }
            })
          } else {
            wx.showToast({
              title: '图片检测失败，请重试',
              success: () => {
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              }
            })
          }
        }
      })
    })
  },

  /**
   * 拍摄事件
   */
  takePhoto: function () {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: async (res) => {
        console.log(res)
        this.setData({
          canvasWidth: res.width,
          canvasHeight: res.height,
          tempImagePath: res.tempImagePath
        })
        // 先图片内容安全检测
        // let checkResult = await this.checkImage(imageUrl)
        // if(checkResult==0){}

        let addWatermark = await this.addWatermark(res.tempImagePath)
        let tempfile = await this.uploadFile(addWatermark)
        // wx.previewImage({
        //   urls: [addWatermark],
        // })
        this.setData({
          tempImagePath: 'addWatermark'
        })
        this.addImgs(tempfile)
       
      }
    })
  },

  /**
   * 给图片添加水印
   */
  addWatermark: function (imageUrl) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '图片生成中...',
      })
      const query = wx.createSelectorQuery();
      query.select('#canvas').fields({
        node: true,
        size: true
      }).exec((res) => {
        console.log(res)
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const dpr = wx.getSystemInfoSync().pixelRatio;
        const {
          canvasWidth,
          canvasHeight
        } = this.data;
        canvas.width = canvasWidth * 0.6
        canvas.height = canvasHeight * 0.6
        ctx.scale(0.6, 0.6)
        var that = this;
        // 绘制背景图片
        const image = canvas.createImage();
        image.onload = () => {
          ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);
          ctx.font = 'normal 32px null';
          ctx.fillStyle = '#ffffff';
          ctx.textBaseline = 'bottom';
          // 绘制一机宝水印
          if(that.data.remarks){
            ctx.fillText('备注：'+that.data.remarks, 20, canvasHeight - 20);
          }
          ctx.fillText('一机宝水印相机已验证时间真实性', 20, canvasHeight - 65);
          // 绘制地址
          ctx.fillText(this.data.address, 20, canvasHeight - 115);
          // 绘制时间
          ctx.fillText(this.data.date + ' ' + this.data.time, 20, canvasHeight - 165);
          // 绘制星期
          ctx.fillText(this.data.week, 20, canvasHeight - 215);
          
          wx.canvasToTempFilePath({
            canvas,
            success: (res) => {
              wx.hideLoading()
              wx.compressImage({
                src: res.tempFilePath,
                quality: 10,
                compressedWidth:canvasWidth/2,
                compressedHeight:canvasHeight/2,
                success: function(res) {
                  resolve(res.tempFilePath);
                }
             })
            },
            fail: () => {
              wx.hideLoading()
              reject(new Error('转换为图片失败'));
            }
          });
        }
        image.src = imageUrl;
      });
    });
  },

  /**
   * 切换摄像头
   */
  setDevice: function () {
    this.setData({
      device: this.data.device == 'back' ? 'front' : 'back'
    })
    let text = this.data.device == 'back' ? '后置' : "前置";
    wx.showToast({
      title: "摄像头" + text
    })
  },
  uploadFile(file_path) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '上传中...',
      })
      console.log(file_path)
      wx.uploadFile({
        filePath: file_path,
        name: 'file',
        url:config.REQUEST_JAVA_LIST.DEV+ '/file/upload',
        header: {
          Authorization: wx.getStorageSync('token')
        },
        success(response) {
          var res = JSON.parse(response.data)
          wx.showToast({
            title: '上传成功',
          })
          var data = {
            url: res.data.url,
            id: res.data.id
          }
          resolve(data)
        },
        fail(error) {
          wx.showToast({
            title: '上传失败',
          })
          reject(error)
        },
        complete() {
          wx.hideLoading()
        }
      })
    })
  },
  addImgs(file) {
    var pages = getCurrentPages()
    let prevpage = pages[pages.length - 2];
    console.log(prevpage)
    var submitFileList = prevpage.data.submitFileList
    var submitFileIdList= prevpage.data.submitFileIdList
    var imgs= prevpage.data.imgs
    imgs.push({
      id:file.id,
      url:file.url
    })
    submitFileList.push(file.url)
    submitFileIdList.push(file.id)
    prevpage.setData({
      submitFileList: submitFileList,
      submitFileIdList:submitFileIdList,
      imgs:imgs
    })
    prevpage.addimgs()
    console.log(prevpage)
    wx.navigateBack()
  },
  /**
   * 闪光灯开关
   */
  setFlash: function () {
    // this.uploadFile()
    this.setData({
      flash: this.data.flash == 'torch' ? 'off' : 'torch'
    })
  },

  /**
   * 选择位置信息
   */
  chooseLocation: function () {
    wx.chooseLocation({
      success: res => {
        console.log(res)
        this.setData({
          address: res.address
        })
      },
      fail: err => {
        console.log(err)
      }
    })

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onShareTimeline() {

  }
})